<template>
  <div class="container">
    <div class="statistics-overview" v-loading="formReportLoading" v-if="formReport">
      <div class="overview-content">
        <div class="left">
          <div class="answer-count">
            <span class="label">收到答卷</span>
            <span class="value">{{ formReport.curAnswerNum }}</span>
          </div>
          <div class="source">
            <span class="label">来源：</span>
            <span class="value">{{ resourceName }}</span>
          </div>
        </div>
        <div class="right">
          <el-button @click="showExport = true">下载报告</el-button>
          <el-button @click="clearReport">清空数据</el-button>
        </div>
      </div>
    </div>
    <el-scrollbar :max-height="props.maxHeight">
      <div class="card-box" v-loading="formReportLoading">
        <el-tabs v-model="activeName">
          <el-tab-pane label="分类筛选" :name="1" v-if="props.showTab != 1"></el-tab-pane>
          <el-tab-pane label="统计报表" :name="0" v-if="props.showTab != 2"></el-tab-pane>
        </el-tabs>
        <div class="top">
          <div class="status">
            <span>状态：</span>
            <el-select v-model="searchForm.status" @change="handleStatusChange" size="small" style="width: 120px">
              <el-option v-for="item in statusOption" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <div class="resource">
            <span>来源：</span>
            <el-select v-model="searchForm.resource" @change="handleResourceChange" size="small" style="width: 120px">
              <el-option v-for="item in resourceOption" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <el-button type="primary" link @click="handleAddParams" :disabled="addParams.length === cmpOption.length">
            筛选条件
            <el-icon><CirclePlus /></el-icon>
          </el-button>
          <div class="search-filter">
            <div class="state" v-for="(params, paramsIndex) of addParams" :key="paramsIndex">
              <el-select
                v-model="params.cmpKey"
                clearable
                style="width: 240px; margin-right: 8px;"
                @change="
                  val => {
                    cmpChange(val, paramsIndex)
                  }
                "
              >
                <el-option v-for="item in cmpOption" :key="item.value" :label="item.label" :value="item.value" :disabled="addParams.find(param => param.cmpKey === item.value) ? true : false" />
              </el-select>
              <el-select v-if="likeRadio(params)" v-model="params.value" clearable multiple style="width: 240px">
                <el-option v-for="item in params.cmp.default" :key="item.label" :label="item.label" :value="item.label" />
              </el-select>
              <el-input v-if="likeInput(params)" v-model="params.value" placeholder="输入关键词" clearable style="width: 240px"></el-input>
              <el-button class="delete-item" type="primary" link @click="deleteSearchParams(paramsIndex)">
                <el-tooltip class="box-item" effect="dark" content="删除条件" placement="top-start">
                  <i class="iconfont">&#xe74b;</i>
                </el-tooltip>
              </el-button>
            </div>
            <div class="btns" v-if="addParams.length">
              <el-button type="primary" @click="handleSearch">筛选</el-button>
              <el-button type="" @click="reset">清空</el-button>
            </div>
          </div>
        </div>
        <!-- 统计报表 -->
        <div class="statistic-report" v-if="activeName == 0">
          <statisticReport v-loading="formReportLoading" :formReport="formReport" />
        </div>
        <!-- 分类筛选 -->
        <div class="statistic-filter" v-if="activeName == 1">
          <statisticFilter v-loading="formAnalysisLoading" :formAnalysis="formAnalysis" :formReport="formReport" @refreshData="refreshData">
            <!-- <template #footer-pagenation>
              <el-pagination
                class="statistic-filter-pagenation"
                v-model:current-page="formAnalysisParams.currentPage"
                v-model:page-size="formAnalysisParams.pageSize"
                :page-sizes="[10, 30, 50, 100]"
                :small="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="formAnalysisParams.total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </template> -->
          </statisticFilter>
        </div>
      </div>
    </el-scrollbar>

    <!-- 导出对话框 -->
    <el-dialog v-model="showExport" title="导出" width="30%" align-center :inline="true">
      <el-form label-width="230px" label-position="left">
        <el-form-item label="是否导出当前图表所展示的数据?">
          <el-radio-group v-model="exportType">
            <el-radio label="0" size="small" style="margin-right: 10px">excel</el-radio>
            <el-radio label="1" size="small" style="margin-right: 10px">zip</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showExport = false">取消</el-button>
          <el-button type="primary" @click="downLoadReport">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
/* eslint-disable */
import { computed, ref, reactive } from 'vue'
import statisticReport from '@/views/form/manage/components/statistics/statisticReport.vue'
import statisticFilter from '@/views/form/manage/components/statistics/statisticFilter.vue'
import { getFormStatistics, getCurFormInfo, getFormAnalysisData, getCustomSource, clearFormStatistics } from '@/api/formDesign'
import { CirclePlus } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { export2ExcelWithLinks, exportWordZip } from '@/utils/export.js'
import { fileSecretKey } from '@/views/form/manage/design/config/formCmpConfig.js'

const props = defineProps({
  formId: {
    type: [String, Number]
  },
  showTab: {
    type: Number,
    default: 0
  },
  qsList: {
    type: Array,
    default: () => {
      return []
    }
  },
  maxHeight: {
    type: String,
    default: '60vh'
  }
})
const activeName = ref(1)
if (props.showTab == 2) activeName.value = 1
const resourceOption = ref()
// 获取来源列表
const getResourceList = async () => {
  let res = await getCustomSource({ formId: props.formId })
  resourceOption.value = res.data.map(item => {
    return {
      label: item.sourceName,
      value: item.sourceId
    }
  })
  resourceOption.value = [{ label: '全部', value: 0 }, ...resourceOption.value]
}
getResourceList()
const resourceName = computed(() => {
  return resourceOption.value?.find(item => item.value == searchForm.value.resource)?.label || '全部'
})

const statusOption = ref([
  { label: '全部', value: 0 },
  { label: '已通过', value: 1 },
  { label: '未通过', value: 2 }
])
const likeRadio = params => {
  if (params.cmp?.type == 'radio' || params.cmp?.type == 'checkbox' || params.cmp?.type == 'selectSingle' || params.cmp?.type == 'selectMultiple' || params.cmp?.type == 'vote') {
    return true
  }
}
const likeInput = params => {
  if (params.cmp?.type == 'input' || params.cmp?.type == 'textarea') {
    return true
  }
}
const defaultParams = {
  formId: props.formId,
  resource: 0, //来源
  status: 0 //状态
}
const defaultSearchParams = { cmpKey: '', value: null }
const addParams = ref([])
// 增加条件
const handleAddParams = () => {
  addParams.value.push(JSON.parse(JSON.stringify(defaultSearchParams)))
}
// 删除条件
const deleteSearchParams = index => {
  addParams.value.splice(index, 1)
}
const qsStatusOption = ref([
  //状态字体和按钮样式
  { label: '全部', value: 100 },
  { label: '待审核', value: 0, backgroudColor: '#ee7755', color: '#2CBF77' },
  { label: '审核中', value: 1, backgroudColor: '#ee7755', color: '#2CBF77' },
  { label: '已发布', value: 2, backgroudColor: '#2CBF77', color: '#2CBF77' },
  { label: '未通过', value: 3, backgroudColor: '#F00', color: '#2CBF77' },
  { label: '已下线', value: 4, backgroudColor: '#AAAAAA', color: '#FF9700' },
  { label: '即将下线', value: 51, backgroudColor: '#FF9700', color: '#FF9700' }
])

const formReport = ref({})
const searchForm = ref(JSON.parse(JSON.stringify(defaultParams)))
const formReportLoading = ref(false)
// 整理搜索参数
const getAddParams = params => {
  let data = {}
  params.forEach(item => { 
    data[item.cmpKey] = item.value
  })
  return data
}
// 获取统计报表
const handleGetFormReport = async () => {
  formReportLoading.value = true
  // let params = { ...searchForm.value, addParams: getAddParams(addParams.value) }
  let res = await getFormStatistics(getAddParams(addParams.value), searchForm.value)
  let curObj = qsStatusOption.value.find(item => item.value == res.data.status)
  formReport.value = { ...res.data, statusInfo: curObj } //处理得到当前表单状态信息
  formReportLoading.value = false
}
handleGetFormReport()

// 获取统计分析
const formAnalysisParams = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})
const formAnalysis = ref({
  list: {
    formAnalysisData: []
  }
})
const formAnalysisLoading = ref([])
const handleGetFormAnalysisData = async () => {
  formAnalysisLoading.value = true
  // let params = { ...searchForm.value, addParams: getAddParams(addParams.value), ...formAnalysisParams.value }
  let res = await getFormAnalysisData(getAddParams(addParams.value), {...searchForm.value, ...formAnalysisParams.value})
  formAnalysis.value = res.data
  // 去除二级标题
  try {
    formAnalysis.value.formAnalysisProp = formAnalysis.value.formAnalysisProp.filter(item => item.prop.indexOf('secondTitle') === -1)
  } catch (error) {
    console.log(error)
  }
  formAnalysisParams.value.total = res.data.total
  formAnalysisLoading.value = false
  // formReport.value.curAnswerNum = res.data.total
}
handleGetFormAnalysisData()
const handleSizeChange = size => {
  formAnalysisParams.value.pageSize = size
  handleGetFormAnalysisData()
}
const handleCurrentChange = page => {
  formAnalysisParams.value.currentPage = page
  handleGetFormAnalysisData()
}
const handleStatusChange = () => {
  if (activeName.value == 0) {
    handleGetFormReport()
  } else {
    handleGetFormAnalysisData()
  }
}
// 来源
const handleResourceChange = () => {
  if (activeName.value == 0) {
    handleGetFormReport()
  } else {
    handleGetFormAnalysisData()
  }
}
const curFormInfo = ref({})
const cmpOption = ref([])
// 获取当前表单模板信息
const handleGetCurFormInfo = async () => {
  let res = await getCurFormInfo({ formId: props.formId })
  curFormInfo.value = res.data
  let _arr = res.data.formItemList.filter(item => item.type != 'imgUpload' && item.type != 'fileUpload' && item.type != 'pagenation')
  cmpOption.value = _arr.map(cmp => {
    return {
      label: `${cmp.labelIndex}、${cmp.label}`,
      value: cmp.formItemId
    }
  })
}
handleGetCurFormInfo()

// 条件筛选处理
const cmpChange = (val, paramsIndex) => {
  addParams.value[paramsIndex].value = null
  let curCmp = curFormInfo.value.formItemList.find(item => item.formItemId === val)
  if (curCmp) addParams.value[paramsIndex].cmp = curCmp
}
const handleSearch = () => {
  if (activeName.value == 0) {
    handleGetFormReport()
  } else {
    handleGetFormAnalysisData()
  }
}
// 清空条件 重置
const reset = () => {
  addParams.value = []
  handleGetFormAnalysisData()
}
// 下载报告
const showExport = ref(false)
const exportType = ref()
const downLoadReport = async () => {
  // let params = { ...searchForm.value, addParams: getAddParams(addParams.value), ...formAnalysisParams.value }
  let res = await getFormAnalysisData(getAddParams(addParams.value), {...searchForm.value, ...formAnalysisParams.value})
  if (res.code == 20000) {
    let headerProperties = {}
    res.data.formAnalysisProp.forEach(item => {
      if (item.prop.indexOf('secondTitle') === -1) {
        headerProperties[item.prop] = item.label
      }
    })
    if (exportType.value === '0') {
      export2ExcelWithLinks(res.data.list.formAnalysisData, headerProperties, ['fileUpload', 'imgUpload'], new Date().getTime() + '.xlsx')
    } else {
      const fileData = addQuestionAndResult(res.data.list.formAnalysisData, headerProperties)
      exportWordZip(fileData, formReport.value.title)
    }
    showExport.value = false
  }
}
//word数据处理
function addQuestionAndResult(data, questions) {
  return data.map(obj => {
    let genFolder = false //是否创建文件夹
    const questionAndResult = []
    for (const prop in obj) {
      if (!['index', 'answerTime', 'resource', 'ip'].includes(prop) && questions.hasOwnProperty(prop)) {
        let question = questions[prop]
        let result = obj[prop]
        let hasFile = false //是否有文件
        if (prop.includes('Upload')) {
          result.forEach(async item => (item.url += fileSecretKey))
          hasFile = true
          genFolder = true
        }
        questionAndResult.push({ question, result, hasFile })
      }
    }

    // 根据 question 中属性值的序号排序
    questionAndResult.sort((a, b) => {
      const indexA = parseInt(a.question.split('、')[0])
      const indexB = parseInt(b.question.split('、')[0])
      return indexA - indexB
    })

    return { ...obj, questionAndResult, genFolder }
  })
}
// 清空数据
const clearReport = () => {
  ElMessageBox.confirm('<div><p style="font-size: 16px;margin-bottom: 15px;">是否清空报告数据？</p><span style="font-size: 14px;color: #FF5240;">清除后数据将无法恢复</span></div>', '清空确认', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(async () => {
    let res = await clearFormStatistics({ formId: props.formId })
    if (res.code == 20000) {
      ElMessage({
        showClose: true,
        message: '操作成功',
        type: 'success'
      })
      handleGetFormReport()
      handleGetFormAnalysisData()
    }
  })
}

// 删除列表数据后进行刷新
const refreshData = () => {
  handleGetFormReport()
  handleGetFormAnalysisData()
}
</script>
<style scoped lang="scss">
.container {
  width: 100%;
  
  .statistics-overview {
    margin: 0 auto 20px;
    padding: 24px;
    background-color: #fff;
    border-radius: 6px;
    box-shadow: 0 0 4px rgba(0, 0, 0, 0.05);

    .overview-content {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .left {
        display: flex;
        align-items: center;
        gap: 40px;

        .answer-count {
          .label {
            font-size: 14px;
            color: #666;
            margin-right: 8px;
          }
          .value {
            font-size: 24px;
            font-weight: bold;
            color: #2cbf77;
          }
        }

        .source {
          .label {
            font-size: 14px;
            color: #666;
          }
          .value {
            font-size: 14px;
            color: #333;
          }
        }
      }

      .right {
        display: flex;
        gap: 12px;
      }
    }
  }

  .card-box {
    margin: 0 auto;
    padding: 24px;
    background-color: #ffffff;
    border-radius: 6px;
    box-shadow: 0 0 4px rgba(0, 0, 0, 0.05);
    box-sizing: border-box;

    .top {
      position: relative;
      font-size: 14px;
      color: #666;
      
      .status {
        position: absolute;
        top: -47px;
        right: 180px;
      }
      
      .resource {
        position: absolute;
        top: -47px;
        right: 0;
      }
      
      .search-filter {
        margin-top: 10px;
        .state {
          margin: 10px 0;
        }
      }
    }
    .statistic-report,
    .statistic-filter {
      min-height: 400px;
    }
  }
}

.statistic-filter-pagenation {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 10px;
}
</style>
